<?php
namespace app\common\model;
use think\facade\Db;
use think\Model;

class TableField extends Model
{
    // 模型初始化
    protected static function init()
    {
        //TODO:初始化内容
    }
    /**
     * 关联分类
     * @return \think\model\relation\BelongsTo
     */
    public function tables()
    {
        return $this->belongsTo(Table::class,'table_id','id');
    }

    /**
     * 字段类型表
     * @return string[]
     */
    static function field_type()
    {
        $list = ['tinyint','smallint','mediumint','int','bigint','date','time','datetime','timestamp','year','float','double','decimal','char','varchar','tinytext','text','mediumtext','longtext'];
        return $list;
    }

    /**
     * 输入框表
     * @return string[]
     */
    static function field_input()
    {
        $list = [
            'input'      => '单行输入框',
            'date'       => '日期输入框',
            'multiline'  => '多行输入框',
            'editor'     => '编辑器',
            'image'      => '单图上传',
            'multiimage' => '多图上传',
            'radio'      => '单选框',
            'checkbox'   => '多选框',
            'select'     => '多选框',
            'label'      => '标签输入框',
            'other'      => '自定义输入框'
        ];
        return $list;
    }

    /*创建数据库，并且主键是aid
    * table 要查询的表名
    */
    static function createTable($table){
        $sql="CREATE TABLE IF NOT EXISTS `$table` (`id` INT NOT NULL primary key)ENGINE = InnoDB;";
        Db::execute($sql);
        self::checkTable($table);
    }
    /*
    * 检测表是否存在，也可以获取表中所有字段的信息
    * table 要查询的表名
    * return 表里所有字段的信息
    */
    static function checkTable($table){
        $sql="desc `$table`";
        $info=Db::execute($sql);
        return $info;
    }
    /*
    * 检测字段是否存在，也可以获取字段信息(只能是一个字段)
    * table 表名
    * field 字段名
    */
    static function checkField($table,$field){
        $sql='desc `$table` $field';
        $info = Db::execute($sql);
        return $info;
    }
    /*
    * 添加字段
    * table 表名
    * info 字段信息数组 array
    * return 字段信息 array
    */
    static function addField($table,$info){
        $sql="alter table `$table` add column";
        $sql.= self::filterFieldInfo($info);
        Db::execute($sql);
        return true;
        //self::checkField($table,$info['name']);
    }
    /*
    * 修改字段
    * 不能修改字段名称，只能修改
    */
    static function editField($table,$info){
        $sql="alter table `$table` modify ";
        $sql.= self::filterFieldInfo($info);
        Db::execute($sql);
        self::checkField($table,$info['name']);
    }
    /*
    * 字段信息数组处理，供添加更新字段时候使用
    * info[name] 字段名称
    * info[type] 字段类型
    * info[length] 字段长度
    * info[isNull] 是否为空
    * info['default'] 字段默认值
    * info['comment'] 字段备注
    */
    static function filterFieldInfo($info){
        if(!is_array($info))
            return
                $newInfo=array();
                $newInfo['name'] = $info['name'];
                $newInfo['type'] = $info['type'];
                switch($info['type']){
                    case 'varchar':
                    case 'char':
                        $newInfo['length'] = empty($info['length'])?'(100)':"(".$info['length'].")";
                        $newInfo['isNull'] = $info['isNull']==1?'NULL':'NOT NULL';
                        $newInfo['default'] = empty($info['default'])?'':'DEFAULT '.$info['default'];
                        $newInfo['comment'] = empty($info['comment'])?'':'COMMENT '."'".$info['comment']."'";
                        break;
                    case 'int':
                        $newInfo['length'] = empty($info['length'])?'(7)':"(".$info['length'].")";
                        $newInfo['isNull'] = $info['isNull']==1?'NULL':'NOT NULL';
                        $newInfo['default'] = empty($info['default'])?'':'DEFAULT '.$info['default'];
                        $newInfo['comment'] = empty($info['comment'])?'':'COMMENT '."'".$info['comment']."'";
                        break;
                    case 'text':
                        $newInfo['length'] = '';
                        $newInfo['isNull'] = $info['isNull']==1?'NULL':'NOT NULL';
                        $newInfo['default'] = '';
                        $newInfo['comment'] = empty($info['comment'])?'':'COMMENT '."'".$info['comment']."'";
                        break;
                }
                $sql = " ".$newInfo['name']." ".$newInfo['type'];
                $sql.= (!empty($newInfo['length']))?($newInfo['length']) .' ':' ';
                $sql.= $newInfo['isNull'].' ';
                $sql.= $newInfo['default'];
                $sql.= $newInfo['comment'];
            return $sql;
    }
    /*
    * 删除字段
    * 如果返回了字段信息则说明删除失败，返回false，则为删除成功
    */
    static function dropField($table,$field){
        $sql="alter table `$table` drop column $field";
        Db::execute($sql);
        self::checkField($table,$field);
    }
    /*
    * 获取指定表中指定字段的信息(多字段)
    */
    static function getFieldInfo($table,$field){
        $info=array();
        if(is_string($field)){
            self::checkField($table,$field);
        }else{
            foreach($field as $v){
                $info[$v]= self::checkField($table,$v);
            }
        }
        return $info;
    }



}